package org.example;

import org.custominterface.plugininterface;

import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class Main {
    public static void main(String[] args) throws MalformedURLException, InterruptedException {
        System.out.println("Hello world!");

        URL urlpath = Main.class.getProtectionDomain().getCodeSource().getLocation();

//        URL url = new URL("file:"+urlpath.getPath()+"plugins/plugin-1.0-SNAPSHOT.jar");
//        URL url = new URL("file:./plugins/plugin-1.0-SNAPSHOT-jar-with-dependencies.jar");
//        URL url = new URL("file:/g:/4.BackEnd/java/sample/sample/jvm/plugins/plugin-1.0-SNAPSHOT.jar");
        while (true){
            URL url = new URL("file:./plugins/plugin-1.0-SNAPSHOT-jar-with-dependencies.jar");
            URLClassLoader urlClassLoader =
                   new URLClassLoader(new URL[]{url},
                           Thread.currentThread().getContextClassLoader());
           Thread.sleep(100);
           try {

                Class<?> aClass = urlClassLoader.loadClass("org.plugin.plugininterfaceImp");
                plugininterface plugininterface = (plugininterface) aClass.getDeclaredConstructor().newInstance();
//                while (true) {
                System.out.println("=================" + plugininterface.returnmessage());
//                Thread.sleep(100);

               urlClassLoader = null;
               System.out.println("=================" + plugininterface.returnmessage());
               plugininterface = null;
               aClass = null;
               System.gc();
//            }

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        }
//        URLClassLoader urlClassLoader =
//                new URLClassLoader(new URL[]{url},
//                        Thread.currentThread().getContextClassLoader());



    }
}